<!--应付单列表-->
<template>
  <div class="nissin-list-box">
    <el-container class="template-box">
      <!-- tab切换 -->
      <tabs
        is-new-tabs
        :active-index="tabIndex"
        :tabs-arr="indexTabsArr"
        @returnIndex="tabsHandle"
      />
      <!--搜索-->
      <el-header height="auto">
        <el-form
          ref="form"
          :model="form"
          label-width="80px">
          <div class="searchform">
            <el-form-item label="发票抬头">
              <el-input
                placeholder="请输入"
                v-model="form.invoiceName"
                maxlength="99" />
            </el-form-item>
            <el-form-item label="开票企业">
              <el-input
                placeholder="请输入"
                v-model="form.distributorName"
                maxlength="99" />
            </el-form-item>
            <el-form-item label="发票编号">
              <el-input
                placeholder="请输入"
                v-model="form.invoiceNo"
                maxlength="99" />
            </el-form-item>
            <el-form-item label="发票金额">
              <div class="purchasemoney">
                <el-input
                  placeholder="请输入"
                  v-model="form.beginAmount"
                  onkeyup="value=value.replace(/[^\d.]/g,'')"
                  @blur="deal('beginAmount')"
                />-
                <el-input
                  placeholder="请输入"
                  v-model="form.endAmount"
                  onkeyup="value=value.replace(/[^\d.]/g,'')"
                  @blur="deal('endAmount')"
                />
              </div>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                range-separator="-"
                format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
            <div class="searchButtonList">
              <el-button
                class="reset"
                @click.stop="reset">
                <i class="el-icon-refresh-right" />
                重置
              </el-button>
              <el-button
                class="submit"
                type="primary"
                @click.stop="search"
                :class="{'isAddWidth':submitLoading}"
                :loading="submitLoading"
              >
                <i
                  class="el-icon-search"
                  :class="{'isdisplay':submitLoading}" />
                {{ submitLoading?'':'查询' }}
              </el-button>
            </div>
          </div>
        </el-form>
      </el-header>
      <div class="common-ui">
        <p style="text-align:right; margin:8px 0; padding-right:20px;">
          已选发票数：
          <span style="color:red;">{{ checkNum }}</span>&nbsp;;
          金额合计（元）：
          <span style="color:red;">{{ invoiceAllAcount }}</span>
          <!-- 发票总金额：
          <span style="color:red;">{{ invoiceAllAcount }}</span> -->
        </p>
      </div>
      <!-- 列表 -->
      <el-editable
        v-loading="submitLoading"
        :data="dataList"
        height="400"
        :columns="columsData"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="toOrderDetail(scope.row)"
            type="text text-primary">详情</el-button>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
  </div>
</template>

<script>
import {
  hospitalSettleQuaryHospPayList,
  hospitalSettleHospPayStatusCount,
  hospitalSettleCreateTradePayOrder
} from '@const/beforeSettleApi'
import { indexTabsArr, columsData } from './const'
import tabs from '@components/tabs/index.vue'
import ElEditable from '@components/el-editable'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { hasIn, cloneDeep } from 'lodash'
import { formatDate, getFormatterPrice } from '@const/filter'
export default {
  components: { tabs, ElEditable },
  data () {
    return {
      indexTabsArr: cloneDeep(indexTabsArr), // tab切换
      tabIndex: 4, // tab默认值
      form: {}, // 搜索内容
      createTime: [],
      columsData, // 列表表头
      dataList: [], // 列表数据
      checkoutArr: [], // 列表多选
      checkNum: 0, // 多选的个数
      prdAllAcount: 0, // 产品总金额
      invoiceAllAcount: 0, // 发票总金额
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总共的条数
      tabIndexVal: '',
      submitLoading: false
    }
  },
  mounted () {
    this.initNavButtons()
    this.getList()
    this.getCount()
  },
  methods: {
    // 获取列表
    async getList () {
      // console.log('adsa',this.searchData)
      this.submitLoading = true
      const res = await this.$axios({
        method: 'post',
        url: hospitalSettleQuaryHospPayList,
        data: {
          ...this.form,
          orderBussStatus: this.tabIndexVal,
          page: this.curPage,
          pageSize: this.pageSize,
          type: 1
        }
      })
      this.dataList = hasIn(res, ['data', 'payload'])
        ? res.data.payload.content || []
        : []
      this.allAmount = res.data.payload.allAmount
      this.totalElements = res.data.payload.totalElements
      this.submitLoading = false
    },
    // 根据状态获取对应数量
    async getCount () {
      const res = await this.$axios.$get(hospitalSettleHospPayStatusCount)
      let arr = hasIn(res, 'payload') ? res.payload : []

      const cloneIndexTabs = cloneDeep(indexTabsArr)
      let allCount = null // 全部的数量
      arr.forEach(item => {
        allCount += item.orderCount
      })

      // 获取对应tab值
      cloneIndexTabs.forEach(item => {
        arr.forEach(ite => {
          if (ite.orderStatus === item.val) {
            item.badge = { value: ite.orderCount || null }
          }
        })
      })
      cloneIndexTabs[4].badge.value = allCount || null
      this.indexTabsArr = cloneIndexTabs
    },
    // tabs切换处理事件
    tabsHandle (index) {
      this.tabIndexVal =
        this.indexTabsArr[index].val === 'null'
          ? null
          : this.indexTabsArr[index].val
      this.curPage = 1
      this.getList()
    },
    // 搜索功能
    search () {
      let fieldname = ['beginDate', 'endDate']
      if (this.createTime.length !== 0) {
        // 开始时间
        this.form[fieldname[0]] = formatDate(
          this.createTime[0],
          'YYYY-MM-DD HH:mm:ss'
        )
        // 结束时间
        this.form[fieldname[1]] = formatDate(
          this.createTime[1],
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        // 开始时间
        this.form[fieldname[0]] = ''
        // 结束时间
        this.form[fieldname[1]] = ''
      }
      if (this.form.beginAmount === undefined || null || '') {
        this.$set(this.form, 'beginAmount', '')
      }
      if (this.form.endAmount === undefined || null || '') {
        this.$set(this.form, 'endAmount', '')
      }
      this.curPage = 1
      this.getList()
    },
    // 发票金额数字判断处理
    deal (val) {
      if (val === 'beginAmount') {
        // this.form.beginAmount =
        //   this.form.beginAmount === undefined || '' || null || NaN
        //     ? this.$set(this.form, 'beginAmount', '')
        //     : parseFloat(this.form.beginAmount.replace(/[^\d.]/g, ''))
        // this.form.beginAmount = this.form.beginAmount
        if (this.form.beginAmount) {
          this.form.beginAmount = parseFloat(this.form.beginAmount.replace(/[^\d.]/g, ''))
          this.form.beginAmount = this.form.beginAmount ? this.form.beginAmount.toFixed(3) : ''
        } else {
          this.form.beginAmount = this.$set(this.form, 'beginAmount', '')
        }
      } else {
        // this.form.endAmount =
        //   this.form.endAmount === undefined || '' || null || NaN
        //     ? this.$set(this.form, 'endAmount', '')
        //     : parseFloat(this.form.endAmount.replace(/[^\d.]/g, ''))
        if (this.form.endAmount) {
          this.form.endAmount = parseFloat(this.form.endAmount.replace(/[^\d.]/g, ''))
          this.form.endAmount = this.form.endAmount ? this.form.endAmount.toFixed(3) : ''
        } else {
          this.form.endAmount = this.$set(this.form, 'endAmount', '')
        }
      }
    },
    // 搜索重置
    reset () {
      this.form = {}
      this.createTime = []
      this.curPage = 1
      this.getList()
    },
    // 列表多选
    handleSelectionChange (e) {
      this.checkoutArr = e
      this.checkNum = this.checkoutArr.length
      let prdnum = 0
      let invoicenum = 0
      e.forEach(item => {
        prdnum += item.invoiceAmountTax
        invoicenum += item.invoiceAmountTax
      })
      if (prdnum !== 0 || invoicenum !== 0) {
        this.prdAllAcount = getFormatterPrice(prdnum)
        this.invoiceAllAcount =
          invoicenum === 0 ? 0 : getFormatterPrice(invoicenum)
      }
      if (this.checkNum === 0) {
        this.prdAllAcount = 0
        this.invoiceAllAcount = 0
      }
    },
    // 详情
    toOrderDetail (val) {
      this.$router.push({
        path: '/hospitalSide/purchaseManagement/common/invoiceDetails',
        query: {
          id: val.receiptPayId,
          invoiceNo: val.invoiceNo
        }
      })
    },
    generatepaymentnote () {
      let payIdList = this.checkoutArr.map(item => {
        return item.receiptPayId
      })
      if (payIdList.length === 0) {
        this.$message({ type: 'warning', message: '请选择应付单' })
      } else {
        this.$axios
          .$post(hospitalSettleCreateTradePayOrder, {
            payIdList
          })
          .then(res => {
            if (res.msg === 'ok') {
              this.$message({ type: 'success', message: '生成支付单成功' })
            } else {
              this.$message({ type: 'success', message: '生成支付单失败' })
            }
            this.getList()
            this.getCount()
          })
      }
    },
    // 配置按钮
    initNavButtons () {
      // 默认是待审核
      let arr = [
        { type: '', val: '返回', handle: () => this.$router.go(-1) },
        { type: 'primary', val: '生成支付单', handle: this.generatepaymentnote }
      ]
      this.$store.commit('changeLayoutHandle', {
        type: 'btn',
        arr: arr
      })
    },
    // 页码更改
    handleSizeChange (size) {
      this.curPage = 1
      this.pageSize = size
      this.getList()
    },

    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getList()
    }
  }
}
</script>

<style lang="less" scoped>
@import '../m-front-common/pc/assets/var.less';
.nissin-list-box {
  background: @bgColor;
  .el-header {
    background: #fff;
    padding: 8px;
    margin-bottom: 8px;
  }
  .template-box {
    height: 100%;
    overflow: auto;
    /deep/.searchform {
      display: flex;
      flex-wrap: wrap;

      .el-form-item {
        margin-right: 20px;
      }
      .el-input {
        width: 200px;
      }
      .purchasemoney {
        border: 1px solid #dfe2e8;
        padding: 0 2px;
        .el-input__inner {
          border: none;
        }
      }
    }
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
  .common-ui {
    background: #fff;
    margin-bottom: 16px;
  }
}
</style>
